package cn.com.open.itembank.common;


import cn.com.open.itembank.utils.FileUtils;
import cn.com.open.itembank.utils.PathUtil;
import cn.com.open.itembank.utils.StringUtil;
import org.apache.poi.xwpf.usermodel.XWPFRun;


import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The type Common function.
 */
public class CommonFunction {

    /**
     * 表格匹配正则表达式.
     */
    public static final String PATTERN_TABLE_STRING = "<table[^>]*?>[\\s\\S]*?<\\/table>";

    /**
     * 含有附件的正则表达式.
     */
    public static final String PATTERN_ATTACHMENT_STRING = "<[\\s\\S]*? (href|src)=[\\s\\S]*?>";

    /**
     * 标准分隔符.
     */
    public static final String SEPARATOR = "##";

    private CommonFunction() {
    }

    //region 将不含有单引号的逗号分隔字符串变化成为含有单引号的逗号分隔字符串

    /**
     * 将不含有单引号的逗号分隔字符串变化成为含有单引号的逗号分隔字符串.
     *
     * @param orginList 原始的不含有单引号的逗号分隔字符串
     * @return the string
     */
    public static String splitList(String orginList) {

        String comma = ",";
        String returnList = orginList;

        if (!StringUtil.isEmpty(returnList)) {

            if (returnList.startsWith(comma)) {
                returnList = returnList.substring(1);
            }
            if (returnList.endsWith(comma)) {
                returnList = returnList.substring(0, orginList.length() - 1);
            }
            returnList = returnList.trim().replace(comma, "','").replace("]", "'").replace("\\[", "'").replaceAll(" ", "");

            return returnList;
        }
        return null;
    }
    //endregion


    //region ASCII转换为char

    /**
     * ASCII转换为char
     *
     * @param ascii the ascii
     * @return char char
     */
    public static char byteAsciiToChar(int ascii) {
        return (char) ascii;
    }

    /**
     * char转换ASCII.
     *
     * @param chars the chars
     * @return the int
     */
    public static int charToAscii(String chars) {
        if (chars.length() > 1) {
            return -1;
        }
        return (int) chars.charAt(0);
    }

    /**
     * 得到大写字母的序号.
     *
     * @param chars the chars
     * @return the upper case index
     */
    public static int getUpperCaseIndex(String chars) {
        int charAscii = charToAscii(chars);
        if (charAscii < 0) {
            return charAscii;
        }
        return charAscii - 65;
    }
    //endregion

    //region 根据试题模型的i6答案列表得到word格式的答案文本

    /**
     * 根据试题模型的i6答案列表得到word格式的答案文本
     *
     * @param answerList the answer list
     * @return text entry answer data
     */
    public static String getTextEntryAnswerData(List<String> answerList) {
        StringBuilder answerStr = new StringBuilder();

        if (answerList == null || answerList.isEmpty()) {
            return answerStr.toString();
        }

        for (int i = 0; i < answerList.size(); i++) {
            answerStr.append(String.format("%s##", answerList.get(i)));
        }

        answerStr.setLength(answerStr.length() - 2);

        return answerStr.toString();
    }
    //endregion

    //region 格式化成html

    /**
     * 格式化成html.
     *
     * @param orginString the orgin string
     * @return the string
     */
    public static String formatToHtml(String orginString) {
        return orginString.replace("&lt;", "<").replace("&gt;", ">");
    }
    //endregion

    //region 得到文件绝对路径，并且清理给定路径下一天前的文件

    /**
     * 得到文件绝对路径，并且清理给定路径下一天前的文件.
     *
     * @param pathName the path name
     * @param fileName the file name
     * @return the file
     */
    public static String getFileFullPath(String pathName, String fileName) {
        //导出文件夹路径
        String filePath = String.format("%s%s", PathUtil.getBathPath(fileName), pathName);
//        //创建文件夹
//        FileUtils.createDir(filePath);
//        //删除给定文件夹下的最后编辑时间和当前时间差大于1天的历史文件
//        FileUtils.deleteOldFiles(new File(filePath));
        return String.format("%s%s", filePath, fileName);
    }
    //endregion

    //region 从题干或者选项原始内容中获取含有图片的地址列表

    /**
     * 从题干或者选项原始内容中获取含有图片的地址列表，如果是http的则直接返回，如果是本地磁盘的则需要格外关注.
     *
     * @param orginString the orgin string
     * @return the list
     */
    public static List<String> findAttachmentPathList(String orginString) {
        String patternString = "(?<=(href|src)=)(?<Q>\"|')(?<PATH>.*?)\\k<Q>";   //(?<=(href|src)=)(?<Q>"|')(?<PATH>.*?)\k<Q>
        Pattern p = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

        Matcher matcher = p.matcher(orginString);
        List<String> returnList = new ArrayList<>();
        while (matcher.find()) {
            String fullPath = matcher.group("PATH").replace("", "");

            returnList.add(fullPath);
        }
        return returnList;
    }
    //endregion

    //region 得到题干或者选项原始内容中所有表格里面单元格的内容列表

    /**
     * 得到题干或者选项原始内容中所有表格里面单元格的内容列表
     *
     * @param orginTableContent the orgin table content
     * @return the table content
     */
    public static List<List<List<String>>> getTableContent(String orginTableContent) {
        List<List<List<String>>> listTable = new ArrayList<>();

        if (orginTableContent.toLowerCase().indexOf("<table") > -1) {
            orginTableContent = orginTableContent.replaceAll("(?i)<table>", "")
                    .replaceAll("(?i)<thead>", "")
                    .replaceAll("(?i)</thead>", "")
                    .replaceAll("(?i)<tbody>", "")
                    .replaceAll("(?i)</tbody>", "")
                    .replaceAll("(?i)<tfoot>", "")
                    .replaceAll("(?i)</tfoot>", "")
                    .replaceAll("(?i)<th>", "<td>")
                    .replaceAll("(?i)</th>", "</td>");
            String[] arrayTable = orginTableContent.split("(?i)</table>");

            for (int i = 0; i < arrayTable.length; i++) {
                String trStr = arrayTable[i].replaceAll("(?i)<tr>", "");
                String[] arrayTrs = trStr.split("(?i)</tr>");
                List<List<String>> listTr = new ArrayList<>();

                for (int j = 0; j < arrayTrs.length; j++) {
                    String tdStr = arrayTrs[j].replaceAll("(?i)<td>", "");
                    String[] arrayTds = tdStr.split("(?i)</td>");
                    List<String> listTd = new ArrayList<>();

                    for (int k = 0; k < arrayTds.length; k++) {
                        listTd.add(arrayTds[k]);
                    }
                    listTr.add(listTd);
                }
                listTable.add(listTr);
            }
        }

        return listTable;
    }
    //endregion

    //region 得到题干或者选项原始内容中所有不含指定匹配内容的内容列表

    /**
     * 得到题干或者选项原始内容中所有不含指定匹配内容的内容列表.
     *
     * @param orginTableContent 原始字符串
     * @param patternString     匹配字符串
     * @return the string [ ]
     */
    public static String[] getNonPatternContent(String orginTableContent, String patternString) {
        Pattern p = Pattern.compile(patternString);
        return p.split(orginTableContent);
    }
    //endregion

    //region 得到给定路径中的图片文件名

    /**
     * 得到给定路径中的图片文件名.
     *
     * @param orginString the orgin string
     * @return the img file name
     */
    public static String getImgFileName(String orginString) {
        String suffixes = "jpeg|jpg|png";
        Pattern pat = Pattern.compile("[\\w]+[\\.](" + suffixes + ")");//正则判断
        Matcher matcher = pat.matcher(orginString);//条件匹配
        while (matcher.find()) {
            String substring = matcher.group();//截取文件名后缀名
            if (substring.length() > 0) {
                return substring;
            }
        }

        return "";
    }
    //endregion

    //region 得到根据分隔符拆分的内容集合

    /**
     * 得到根据分隔符拆分的内容集合.
     *
     * @param originalString 含有分隔符的内容原始文本
     * @param separator      分隔符
     * @return the list
     */
    public static List<String> getList(String originalString, String separator) {
        return Arrays.asList(originalString.split(separator));
    }

    /**
     * Gets list remove empty entities.
     *
     * @param originalString the original string
     * @param separator      the SEPARATOR
     * @return the list remove empty entities
     */
    public static List<String> getListRemoveEmptyEntities(String originalString, String separator) {
        List<String> list = getList(originalString, separator);
        List<String> result = new ArrayList<>();
        for (String str : list) {
            if (str.trim().length() != 0) {
                result.add(str);
            }
        }

        return result;
    }
    //endregion

    //region 得到文件扩展名

    /**
     * 得到文件扩展名.
     *
     * @param filePath the file path
     * @return the ext name
     */
    public static String getExtName(String filePath) {
        return filePath.substring(filePath.lastIndexOf('.'));
    }
    //endregion

    //region 用标准分隔符拼接字符串集合

    /**
     * 用标准分隔符拼接字符串集合.
     *
     * @param stringList the string list
     * @return the each list
     */
    public static String getEachList(List<String> stringList) {
        return String.join(SEPARATOR, stringList);
    }
    //endregion

    //region 根据试题模型的i7答案列表得到word格式的答案文本

    /**
     * 根据试题模型的i7答案列表得到word格式的答案文本
     *
     * @param answerList the answer list
     * @return answer data
     */
    public static String getAnswerData(List<String> answerList) {
        StringBuilder answerStr = new StringBuilder();

        if (answerList == null || answerList.isEmpty()) {
            return answerStr.toString();
        }

        for (int i = 0; i < answerList.size(); i++) {
            if (i != 0)
                answerStr.append(", ");
            answerStr.append(String.format("%s", Function.byteAsciiToChar(65 + Integer.valueOf(answerList.get(i)))));
        }

        return answerStr.toString();
    }
    //endregion

    //region 剔除HTML标签

    /**
     * 剔除HTML标签
     *
     * @param content
     */
    public static String processeHTML(String content) {
        Pattern pHtml = Pattern.compile("<[.[^>]]*>", Pattern.CASE_INSENSITIVE);
        Matcher mHtml = pHtml.matcher(content);  // 过滤html标签
        return mHtml.replaceAll("");
    }
    //endregion
    //region 根据试题模型的i6选项列表得到word格式的选项文本

    /**
     * 根据试题模型的i6选项列表得到word格式的选项文本
     *
     * @param optionList the option list
     * @return choice data
     */
    public static void getChoiceData(List<String> optionList, XWPFRun run) {
        if (optionList == null || optionList.isEmpty()) {
            return;
        }

        for (int i = 0; i < optionList.size(); i++) {
            run.setText(String.format("%s.%s", Function.byteAsciiToChar(65 + i), processeHTML(optionList.get(i))));
            run.addBreak();
        }
    }
    //endregion
}
